package utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import org.apache.http.NameValuePair;

public class ServiceHandler {
	static String response = null;

	public ServiceHandler() {

	}

	/**
	 * Making service call
	 * 
	 * @url - url to make request
	 * @method - http get request method
	 * */
	public String executeGetRequest(String url) {
		return this.executeGetRequest(url, null);
	}

	/**
	 * Making service call
	 * 
	 * @url - url to make request
	 * @method - http get request method
	 * @params - http request params
	 * */
	public String executeGetRequest(String url, List<NameValuePair> params) {
		response = null;
		try {
			URL urlGet = new URL(url);
			URLConnection connection = urlGet.openConnection();
			connection.setDoInput(true);
			connection.setRequestProperty("Content-Type", "application/json");
			//connection.setConnectTimeout(15000);
			//connection.setReadTimeout(15000);

			StringBuilder sb = new StringBuilder();
			try {
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(connection.getInputStream()));
				String line = null;
				// Read Server Response
				while ((line = reader.readLine()) != null) {
					// Append server response in string
					sb.append(line);
				}
				reader.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			response = sb.toString();

		} catch (Exception e) {
			e.printStackTrace();
		}
		return response;
	}

	/**
	 * @method - http post request method
	 * */
	public String executePostRequest(String url, String json) {
		response = null;

		try {
			String paramString = json;
			URL urlPost = new URL(url);
			URLConnection connection = urlPost.openConnection();
			connection.setDoOutput(true);
			connection.setRequestProperty("Content-Type", "application/json");
			//connection.setConnectTimeout(15000);
			//connection.setReadTimeout(15000);
			OutputStreamWriter wr = new OutputStreamWriter(
					connection.getOutputStream());
			wr.write(paramString);
			wr.close();
			// Get the server response

			StringBuilder sb = new StringBuilder();
			try {
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(connection.getInputStream()));
				String line = null;
				// Read Server Response
				while ((line = reader.readLine()) != null) {
					// Append server response in string
					sb.append(line);
				}
				reader.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			response = sb.toString();

		} catch (Exception e) {
			e.printStackTrace();
		}
		return response;
	}
}
